﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Security.Principal;
using OpenRasta.OperationModel.Interceptors;
using OpenRasta.Web;
using OpenRasta.OperationModel;
using umbraco;
using umbraco.BusinessLogic;
using uREST.Core.Extensions;

namespace uREST.Core.Interceptors
{
    public class UmbracoAuthorizeInterceptor : OperationInterceptor
    {
        private readonly ICommunicationContext _context;
        private string[] _applications;

        public UmbracoAuthorizeInterceptor(ICommunicationContext context, string[] applications)
        {
            _context = context;
            _applications = applications;
        }

        public override bool BeforeExecute(IOperation operation)
        {
            //if (UmbracoSettings.Webservices.Enabled)
            //{
                var queryParams = HttpUtility.ParseQueryString(_context.Request.Uri.Query);
                if (queryParams["auth_username"] != null && queryParams["auth_token"] != null)
                {
                    try
                    {
                        var user = new User(queryParams["auth_username"]);
                        if (user.LoginName == queryParams["auth_username"])
                        {
                            if (user.Tokenize() == queryParams["auth_token"])
                            {
                                _context.User = new GenericPrincipal(new GenericIdentity(user.LoginName), new[] { user.UserType.Alias });

                                if (_applications != null && _applications.Length > 0)
                                    return user.Applications.Any(app => _applications.Contains(app.alias.ToLower()));

                                return true;
                            }
                        }
                    }
                    catch { }
                }
            //}

            _context.OperationResult = new OperationResult.Forbidden();
            return false;
        }
    }
}
